package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.entity.dto.UserDTO;
import com.example.entity.item.*;
import com.example.entity.item.dto.FreeWithItemDTO;
import com.example.entity.market.Market;
import com.example.entity.order.Order;
import com.example.entity.order.OrderItem;
import com.example.entity.user.Room;
import com.example.entity.user.User;
import com.example.entity.user.UserAddresses;
import com.example.entity.user.mailAccount;
import com.example.exception.CustomException;
import com.example.mapper.UserMapper;
import com.example.mapper.dao.FarmDao;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private FarmDao farmDao;

    //获取用户信息
    public UserDTO GetUserInfo(String UID){return userMapper.GetUserInfo(UID);}

    //删除用户
    public void deleteUserById(String UID)
    {
        userMapper.deleteUserById(UID);
    }

    //更新用户资料
    public void updateUserById(User user){userMapper.updateUserById(user);}

    //ID查询用户
    public User selectUserById(String UID){return userMapper.selectUserById(UID);}

    //ID查询商品图片表
    public List<item_images> selectItemUrlById(String itemId){return userMapper.selectItemUrlById(itemId);}

    //ID查询商品
    public FreeWithItemDTO selectItemById(String itemId){
        FreeWithItemDTO freeWithItemDTO=userMapper.selectItemByIdWithFree(itemId);
        if(farmDao.isFreeItem(itemId)>0)
        {
            freeWithItemDTO.setFree(true);
        }
        else
        {
            freeWithItemDTO.setFree(false);
        }
        return freeWithItemDTO;
    }

    //查询用户收获地址
    public List<UserAddresses> selectUserAddressAll(String UID){return userMapper.selectUserAddressAll(UID);}

    //添加用户收货地址
    public void AddUserAddress(UserAddresses userAddresses)
    {
        userMapper.AddUserAddress(userAddresses);
    }

    //查询所有用户
    public List<User> selectUserAll(User user){return userMapper.selectUserAll(user);}

    //分页查询用户
    public PageInfo<User> selectUserPage(User user, Integer pageNum, Integer pageSize)
    {
        PageHelper.startPage(pageNum,pageSize);
        List<User> list=userMapper.selectUserAll(user);
        return PageInfo.of(list);
    }

    //查询所有行情
    public List<Market> selectMarket(Market market)
    {
        return userMapper.selectMarket(market);
    }

    //分页行情查询
    public PageInfo<Market> selectMarketPage(Market market,Integer pageNum,Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<Market> list=userMapper.selectMarket(market);
        return PageInfo.of(list);
    }

    //查询热门行情
    public List<Market> selectMarketHot(Market market){return userMapper.selectMarketHot(market);}

    //查询所有商品
    public List<Items> selectItemAll(){return userMapper.selectItemAll();}

    //查询所有商品分类
    public List<itemList> selectItemListAll(){return userMapper.selectItemListAll();}

    //查询用户购物车
    public List<CartItem> selectUserCart(String UID)
    {
        List<Carts> carts=userMapper.selectUserCartById(UID);
        List<CartItem> cartItems=new ArrayList<>();
        for (Carts cart:carts){
            Items item=userMapper.selectItemById(cart.getItemId());
            Room room=userMapper.selectRoomById(item.getItemOwner());
            cartItems.add(new CartItem(cart,item,room));
        }
        cartItems.forEach(pair -> System.out.println(pair.getCart() + " - " + pair.getItem()));
        return cartItems;

    }

    //加入购物车
    public void JoinCart(Carts carts)
    {
       userMapper.JoinCart(carts);
    }

    //删除购物车商品
    public void DeleteCartItem(Integer cartID){userMapper.DeleteCartItem(cartID);}

    //加入收藏夹
    public void JoinFav(Favorites favorites){userMapper.JoinFav(favorites);}

    //判断是否收藏
    public Boolean selectUserFavById(String UID,String itemId)
    {
        Boolean bool= userMapper.selectUserFavByIdAndItemId(UID,itemId);
        return bool;
    }

    //查询收藏夹
    public List<FavoritesItem> selectUserFav(String UID)
    {
        List<Favorites> favorites=userMapper.selectUserFavById(UID);
        List<FavoritesItem> favoritesItems=new ArrayList<>();
        for (Favorites favorites1:favorites){
            Items item= userMapper.selectItemById(favorites1.getItemId());
            favoritesItems.add(new FavoritesItem(favorites1,item));
        }
        return favoritesItems;
    }

    //查询订单
    public List<OrderItem> selectOrder(String UID)
    {
        List<Order> orders=userMapper.selectUserOrderById(UID);
        List<OrderItem> orderItems=new ArrayList<>();
        for(Order order:orders){
            Items item=userMapper.selectItemById(order.getItemId());
            orderItems.add(new OrderItem(order,item));
        }
        orderItems.forEach(pair -> System.out.println(pair.getOrder() + " - " + pair.getItems()));
        return orderItems;
    }

    //提交订单
    public String SubmitOrder(Order order)
    {
        SimpleDateFormat formatter=new SimpleDateFormat("yyyyMMdd");

        //规范订单号格式 yyyyMMdd-用户Id-商品Id
        String order_number;

        //提取用户UID部分
        String uidPart=extractUidPart(order.getUID());

        //格式化订单号
        order_number=formatter.format(order.getCreatedAt())+uidPart+order.getItemId();

        //重置订单号
        order.setTrackingNumber(order_number);

        //更新库存
        Items item=userMapper.selectItemById(order.getItemId());
        if (item == null) {
            throw new IllegalArgumentException("商品不存在");
        }
        Integer newStock= item.getItemStock()-order.getQuantity();
        if (newStock<0){
            throw new IllegalArgumentException("库存不足");
        }
        userMapper.updateItemStock(order.getItemId(),newStock);

        //保存订单
        userMapper.SubmitOrder(order);
        return order.getTrackingNumber();
    }


    //截取UID
    private String extractUidPart(String uid) {
        // 假设UID格式为UUID，即32位字符，可以按照如下方式提取UID的前8位
        if(uid==null||uid.length()<8){
            throw new IllegalArgumentException("UID需要至少8位");
        }
        return uid.substring(0, 8);
    }

    //付款与否
    public void IfPay(String trackingNumber,String state)
    {
        System.out.println(trackingNumber+"and"+state);
        if (state.equals("success"))
        {
            System.out.println("我成功了");
            userMapper.OrderStatus(trackingNumber,"待发货");
        }
        else if(state.equals("failure"))
        {
            System.out.println("付款失败");
        }
        else
        {
            System.out.println("参数错误");
        }
    }


    /**
     * 注册
     */
    public void register(User user)
    {
        user.setUID(UUID.randomUUID().toString().replace("-", ""));
        User dbAdmin=userMapper.selectUserByUsername(user.getUsername());
        System.out.println(dbAdmin);
        if (ObjectUtil.isNotNull(dbAdmin))
        {
            throw new CustomException("用户已存在");
        }
        if(ObjectUtil.isEmpty(user.getName()))
        {
            user.setName(user.getUsername());
        }
        user.setRole("USER");
        userMapper.insert(user);
    }


    /**
     * 保存验证码
     */
    public void save_code(String mailAddress,String code){
        userMapper.updateEmailCode(mailAddress,code);
    }

    /**
     * 邮箱登录
     */
    public mailAccount email_login(mailAccount mailaccount){
        mailAccount dbUser=null;
        dbUser=userMapper.selectByEmailAddress(mailaccount.getMailAddress());
        if (ObjectUtil.isNull(dbUser)){
            throw new CustomException("用户不存在");
        }
        //这里需要补充验证码错误的情况
        return dbUser;
    }

    /**
     * 邮箱注册
     */
    public void email_register(mailAccount mailaccount){
        Random random = new Random();
        int number = random.nextInt(900) + 100; // 生成10000到99999之间的随机数
        mailAccount dbMail=userMapper.selectByEmailAddress(mailaccount.getMailAddress());
        System.out.println(dbMail);
        if(ObjectUtil.isNotNull(dbMail)){
            throw new CustomException("用户已存在");
        }
        if (ObjectUtil.isEmpty(mailaccount.getName())){
            mailaccount.setName("用户"+number);
        }
        mailaccount.setRole("USER");
        userMapper.email_insert(mailaccount);
    }

    // 动态查询商品
    public List<Items> findItemsByCategory(String categoryId, String typeId, String classId) {
        List<Items> items=userMapper.findItemsByCategory(categoryId, typeId, classId);

        return items;
    }

    public List<FreeWithItemDTO> findItemsByCategoryWithFree(String categoryId, String typeId, String classId) {

        List<FreeWithItemDTO> items=userMapper.findItemsByCategoryWithFree(categoryId, typeId, classId);
        for (FreeWithItemDTO item : items) {
            if (farmDao.isFreeItem(item.getItemID())>0)
            {
                item.setFree(true);
            }
            else
            {
                item.setFree(false);
            }
        }

        return items;
    }

    // 获取根分类，即一级分类
    public List<Category> getRootCategories() {
        return userMapper.selectRootCategories();  // 父分类 ID 为 NULL，表示一级分类
    }

    // 获取树形结构
    public List<Category> getCategoryTree() {
        List<Category> rootCategories = getRootCategories();
        for (Category rootCategory : rootCategories) {
            // 给每个根分类添加子分类
            rootCategory.setChildren(getSubCategories(rootCategory.getCategoryId()));
        }
        return rootCategories;
    }

    // 获取某个分类的子分类
    public  List<Category> getSubCategories(String parentId) {
        List<Category> subCategories = userMapper.selectSubCategories(parentId);
        for (Category subCategory : subCategories) {
            // 递归调用，获取更多层级的子分类
            subCategory.setChildren(getSubCategories(subCategory.getCategoryId()));
        }
        return subCategories;
    }

    // 根据省份查询市场数据
    public List<Market> getMarketsByProvince(String province) {
        return userMapper.findMarketsByProvince(province);
    }
}
